package 对象的比较方式.基于比较器比较;

/*
Comparator是java.util 包中的泛型接口类，使用时必须导入对应的包
需要实现一个比较器对象，对待比较类的侵入性弱，但对算法代码实现侵入性强
 */

import java.util.Comparator;

class Student {
    String name;
    int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

//用户自定义比较器类，实现Comparator接口
class StudentComparator implements Comparator<Student>{
    //基于年龄比较，不管名字
    // 这里我们认为 null 是最小的
    @Override
    public int compare(Student o1, Student o2) {
        if (o1 == o2) {
            return 0;
        }
        if (o1 == null) {
            return -1;
        }
        if (o2 == null) {
            return 1;
        }
        return o1.age-o2.age;
    }
}


public class Test {
    public static void main(String[] args) {
        Student student=new Student("王五",12);
        Student student1=new Student("王五",13);

        StudentComparator studentComparator=new StudentComparator();
        System.out.println(studentComparator.compare(student,student1));//-1

    }
}
